This is a draft version of a MISRA C++ 202x rule proposed for public review.
MISRA Rule 25.5.1
Category: Required
Analysis Type: Decidable,Single Translation Unit
Rationale
Calls to setlocale
or std::locale::global
may introduce data races (leading to undefined behaviour) with
functions that use the locale (e.g. printf
, tolower
). It is not as easy to guard against these potential data races due to
the ways in which the global locale is used within the C++ Standard Library.
The C++ Standard Library provides functions that allow a locale to be passed as an argument, meaning that it is possible to use a specific locale
without having to depend on the setting of the global locale objects.
Example
void f1()
{
wchar_t c = L'\u2002'; // En-space
std::setlocale( LC_ALL, "ja_JP.utf8" ); // Non-compliant
if ( std::isspace( c ) ) {} // Uses global locale
}
The following example sets the locale without violating this rule:
void f2()
{
wchar_t c = L'\u2002'; // En-space
std::locale utf8( "ja_JP.utf8" );
if ( std::isspace( c, utf8 ) ) {} // Does not use global locale
}
Copyright The MISRA Consortium Limited © 2023